<!doctype html>



  


<html class="theme-next muse use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Timer &amp;amp; TimerTask 作为java的任务调度器之一，了解其内部原理有助于我们更好的理解它与其他调度器之间的异同。


TimerTask
Timer及其调度过程
总结">
<meta property="og:type" content="article">
<meta property="og:title" content="java定时任务（1）">
<meta property="og:url" content="http://yoursite.com/2016/08/28/java定时任务（1）/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="Timer &amp;amp; TimerTask 作为java的任务调度器之一，了解其内部原理有助于我们更好的理解它与其他调度器之间的异同。


TimerTask
Timer及其调度过程
总结">
<meta property="og:updated_time" content="2017-01-19T07:14:13.144Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java定时任务（1）">
<meta name="twitter:description" content="Timer &amp;amp; TimerTask 作为java的任务调度器之一，了解其内部原理有助于我们更好的理解它与其他调度器之间的异同。


TimerTask
Timer及其调度过程
总结">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/08/28/java定时任务（1）/"/>

  <title> java定时任务（1） | 个人博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">个人博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">随便写点什么</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                java定时任务（1）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T15:59:18+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/08/28/java定时任务（1）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/08/28/java定时任务（1）/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<p>Timer &amp; TimerTask 作为java的任务调度器之一，了解其内部原理有助于我们更好的理解它与其他调度器之间的异同。</p>
<blockquote>
<ul>
<li>TimerTask</li>
<li>Timer及其调度过程</li>
<li>总结</li>
</ul>
</blockquote>
<hr>
<a id="more"></a>
<h2 id="TimerTask"><a href="#TimerTask" class="headerlink" title="TimerTask"></a>TimerTask</h2><p><strong>TimerTask</strong>作为被调度任务的抽象类，继承于Thread,但是没有实现<strong>run方法</strong>，而是留给我们根据具体业务需求来实现。</p>
<h3 id="1-TimerTask主要函数"><a href="#1-TimerTask主要函数" class="headerlink" title="1. TimerTask主要函数"></a>1. TimerTask主要函数</h3><ul>
<li>[x] public boolean cancel()；</li>
<li>[x] public long scheduledExecutionTime()；</li>
</ul>
<p><strong>cancel()</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">*设置一个任务的状态位为cancelled，但是并没有从任务队列中删除。</div><div class="line">*而是继续存在于任务队列，调用purge()；方法后会将无效的任务（cancelled）删除。</div><div class="line">**/</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">cancel</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span>(lock) &#123;</div><div class="line">            <span class="keyword">boolean</span> result = (state == SCHEDULED);</div><div class="line">            state = CANCELLED;</div><div class="line">            <span class="keyword">return</span> result;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p><strong>scheduledExecutionTime()</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">*任务最近一次将要被执行的时间。</div><div class="line">*period之所以可以小于0，因为在Timer中设置调度方式式时有两种方案。</div><div class="line">**/</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">scheduledExecutionTime</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">synchronized</span>(lock) &#123;</div><div class="line">            <span class="keyword">return</span> (period &lt; <span class="number">0</span> ? nextExecutionTime + period</div><div class="line">                               : nextExecutionTime - period);</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<hr>
<h2 id="Timer"><a href="#Timer" class="headerlink" title="Timer"></a>Timer</h2><h3 id="1-Timer的调度方法"><a href="#1-Timer的调度方法" class="headerlink" title="1.Timer的调度方法"></a>1.Timer的调度方法</h3><ul>
<li>[ ] schedule(TimerTask task, long delay);</li>
<li>[ ] schedule(TimerTask task, Date time);</li>
<li>[ ] schedule(TimerTask task, long delay, long period);</li>
<li>[ ] schedule(TimerTask task, Date firstTime, long period);</li>
<li>[ ] scheduleAtFixedRate(TimerTask task, long delay, long period);</li>
<li>[ ] scheduleAtFixedRate(TimerTask task, Date firstTime, long period);</li>
<li>[x] sched(TimerTask task, long time, long period);</li>
</ul>
<p><strong>schedule(TimerTask task, long delay):</strong> 当前系统时间延迟delay后执行，只执行一次。</p>
<p><strong>schedule(TimerTask task, Date time):</strong> 在指定的Date执行，只执行一次。</p>
<p><strong>schedule(TimerTask task, long delay, long period):</strong> 当前系统时间延迟delay执行，后续每隔period执行一次，循环执行。</p>
<p><strong>schedule(TimerTask task, Date firstTime, long period):</strong> 第一次执行的时间为Date，后续每隔period执行一次，循环执行。</p>
<p><strong>scheduleAtFixedRate(TimerTask task, long delay, long period):</strong> 同样是当前系统时间延迟delay后执行，每隔period执行一次，循环执行。但是在计算下次执行时间上与schedule()有所不同，比如最近一次执行时间是X，period为5，Timer调度存在3毫秒的延迟，那么由schedule计算出来的下次执行时间为X+5+3，而由scheduleAtFixedRate计算出来的时间仍为X+period，这个下次执行时间会影响Task在任务队列中的位置。</p>
<p><strong>scheduleAtFixedRate(TimerTask task, Date firstTime, long period):</strong> 理解同上。</p>
<p><strong>sched(TimerTask task, long time, long period):</strong> 该函数是以上所有调度方式的内部执行函数，接下来会详细介绍。</p>
<h3 id="2-初始化"><a href="#2-初始化" class="headerlink" title="2.初始化"></a>2.初始化</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line">* TaskQueue queue = new TaskQueue();</div><div class="line">* TaskQueue是Timer的一个内部类，其主要成员为：TimerTask[] queue = new TimerTask[128];</div><div class="line">* 以及提供对该数组的一些操作。</div><div class="line">*</div><div class="line">**/</div><div class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sched</span><span class="params">(TimerTask task, <span class="keyword">long</span> time, <span class="keyword">long</span> period)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (time &lt; <span class="number">0</span>)</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Illegal execution time."</span>);</div><div class="line">        <span class="keyword">if</span> (Math.abs(period) &gt; (Long.MAX_VALUE &gt;&gt; <span class="number">1</span>))</div><div class="line">            period &gt;&gt;= <span class="number">1</span>;</div><div class="line"></div><div class="line">        <span class="keyword">synchronized</span>(queue) &#123;</div><div class="line">            <span class="keyword">if</span> (!thread.newTasksMayBeScheduled)</div><div class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Timer already cancelled."</span>);</div><div class="line"></div><div class="line">            <span class="keyword">synchronized</span>(task.lock) &#123;</div><div class="line">                <span class="keyword">if</span> (task.state != TimerTask.VIRGIN)</div><div class="line">                    <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(</div><div class="line">                        <span class="string">"Task already scheduled or cancelled"</span>);</div><div class="line">                task.nextExecutionTime = time;</div><div class="line">                task.period = period;</div><div class="line">                task.state = TimerTask.SCHEDULED;</div><div class="line">            &#125;</div><div class="line"></div><div class="line">            queue.add(task);</div><div class="line">            <span class="keyword">if</span> (queue.getMin() == task)</div><div class="line">                queue.notify();</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>该函数的意义是用户提交一个任务后，设置好下次执行的时间，时间片（period）大小，任务状态后，加入任务队列，实质是放入一个任务数组。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//实现细节</span></div><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">add</span><span class="params">(TimerTask task)</span> </span>&#123;</div><div class="line">        <span class="comment">// Grow backing store if necessary</span></div><div class="line">        <span class="keyword">if</span> (size + <span class="number">1</span> == queue.length)</div><div class="line">            queue = Arrays.copyOf(queue, <span class="number">2</span>*queue.length);</div><div class="line"></div><div class="line">        queue[++size] = task;</div><div class="line">        fixUp(size);</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    </div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fixUp</span><span class="params">(<span class="keyword">int</span> k)</span> </span>&#123;</div><div class="line">        <span class="keyword">while</span> (k &gt; <span class="number">1</span>) &#123;</div><div class="line">            <span class="keyword">int</span> j = k &gt;&gt; <span class="number">1</span>;</div><div class="line">            <span class="keyword">if</span> (queue[j].nextExecutionTime &lt;= queue[k].nextExecutionTime)</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;</div><div class="line">            k = j;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<p>这里解释下fixUp()，它其实完成的是一个排序功能，但是不是绝对意义上的有序，用相对有序更为恰当，它的目的只是将新的任务放到一个合适的位置。<br>k&gt;&gt;1相当于k/2，这样处理的好处是提高对于大量堆积任务的排序性能，因为他极大的减少了需要排序的次数，同时也保证了一定程度的有序性。试想，每次有新的任务进来时，都要完成一次绝对排序，对于整体性能影响是比较大的。</p>
</blockquote>
<h3 id="3-调度过程"><a href="#3-调度过程" class="headerlink" title="3.调度过程"></a>3.调度过程</h3><p>Timer实际被调用的两个构造函数<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> TimerThread thread = <span class="keyword">new</span> TimerThread(queue);</div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Timer</span><span class="params">(String name)</span> </span>&#123;</div><div class="line">        thread.setName(name);</div><div class="line">        thread.start();</div><div class="line">    &#125;</div><div class="line">    </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Timer</span><span class="params">(String name, <span class="keyword">boolean</span> isDaemon)</span> </span>&#123;</div><div class="line">    thread.setName(name);</div><div class="line">    thread.setDaemon(isDaemon);</div><div class="line">    thread.start();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>TimerThread是Timer的一个内部类，继承Thread，是Timer中真正执行调度动作的线程。但是需要注意的是他是单线程，而非线程池，也就是说，Timer对于任务是串行执行的。</p>
</blockquote>
<p>接下来看下<strong>TimerThread</strong>的run方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            mainLoop();</div><div class="line">        &#125; <span class="keyword">finally</span> &#123;</div><div class="line">            <span class="keyword">synchronized</span>(queue) &#123;</div><div class="line">                newTasksMayBeScheduled = <span class="keyword">false</span>;</div><div class="line">                queue.clear();  </div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">mainLoop</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                TimerTask task;</div><div class="line">                <span class="keyword">boolean</span> taskFired;</div><div class="line">                <span class="keyword">synchronized</span>(queue) &#123;</div><div class="line">                    <span class="keyword">while</span> (queue.isEmpty() &amp;&amp; newTasksMayBeScheduled)</div><div class="line">                        queue.wait();</div><div class="line">                    <span class="keyword">if</span> (queue.isEmpty())</div><div class="line">                        <span class="keyword">break</span>; </div><div class="line">                    <span class="keyword">long</span> currentTime, executionTime;</div><div class="line">                    task = queue.getMin();</div><div class="line">                    <span class="keyword">synchronized</span>(task.lock) &#123;</div><div class="line">                        <span class="keyword">if</span> (task.state == TimerTask.CANCELLED) &#123;</div><div class="line">                            queue.removeMin();</div><div class="line">                            <span class="keyword">continue</span>;  </div><div class="line">                        &#125;</div><div class="line">                        currentTime = System.currentTimeMillis();</div><div class="line">                        executionTime = task.nextExecutionTime;</div><div class="line">                        <span class="keyword">if</span> (taskFired = (executionTime&lt;=currentTime)) &#123;</div><div class="line">                            <span class="keyword">if</span> (task.period == <span class="number">0</span>) &#123; </div><div class="line">                                queue.removeMin();</div><div class="line">                                task.state = TimerTask.EXECUTED;</div><div class="line">                            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                                queue.rescheduleMin(</div><div class="line">                                  task.period&lt;<span class="number">0</span> ? currentTime   - task.period</div><div class="line">                                                : executionTime + task.period);</div><div class="line">                            &#125;</div><div class="line">                        &#125;</div><div class="line">                    &#125;</div><div class="line">                    <span class="keyword">if</span> (!taskFired) </div><div class="line">                        queue.wait(executionTime - currentTime);</div><div class="line">                &#125;</div><div class="line">                <span class="keyword">if</span> (taskFired)  </div><div class="line">                    task.run();</div><div class="line">            &#125; <span class="keyword">catch</span>(InterruptedException e) &#123;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>由上可见，主要的任务轮询发生在mainloopd的while(true)循环中。<br>首先进行 while (queue.isEmpty() &amp;&amp; newTasksMayBeScheduled)循环，第一次运行时，queue必然为空，且newTasksMayBeScheduled初始值为true。所以线程第一次执行时一定会走到 queue.wait()；这里，它会因为任务队列为空而进入等待，相应的，我们可以看到在sched()中提交任务后会有notify()动作来激活该线程。<br>那么继续往下看，为何在激活后又需要判断队列是否为空呢？<br>我们看一段代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">cancel</span><span class="params">()</span> </span>&#123;</div><div class="line">       <span class="keyword">synchronized</span>(queue) &#123;</div><div class="line">           thread.newTasksMayBeScheduled = <span class="keyword">false</span>;</div><div class="line">           queue.clear();</div><div class="line">           queue.notify();  <span class="comment">// In case queue was already empty.</span></div><div class="line">       &#125;</div><div class="line">   &#125;</div></pre></td></tr></table></figure></p>
<p>Timer的cancle()操作，同样会激活线程，所以需要再次检查队列是否为空。而且需要注意的是，再次检查，如果队列为空，则跳出循环，也就是说TimerThread执行结束，调度完毕。<br>若队列不为空，进行queue.getMin()操作，可以认为是取了TimerTask[]数组中的”task head“元素。<br>检查取到的任务的状态，是否为cancel，若是则从队列中删除，继续循环部分。<br>之前提到TimerTask中的cancel()只是更改了标志位，实际的移除在是调用removeMin()来删除的。<br>接下来判断该任务是否满足执行条件。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">currentTime = System.currentTimeMillis();</div><div class="line">executionTime = task.nextExecutionTime;</div><div class="line">                        <span class="keyword">if</span> (taskFired = (executionTime&lt;=currentTime)) &#123;</div><div class="line">                            <span class="keyword">if</span> (task.period == <span class="number">0</span>) &#123; </div><div class="line">                                queue.removeMin();</div><div class="line">                                task.state = TimerTask.EXECUTED;</div><div class="line">                            &#125; <span class="keyword">else</span> &#123; </div><div class="line">                                queue.rescheduleMin(</div><div class="line">                                  task.period&lt;<span class="number">0</span> ? currentTime   - task.period</div><div class="line">                                                : executionTime + task.period);</div><div class="line">                            &#125;</div><div class="line">                        &#125;</div></pre></td></tr></table></figure></p>
<p>意思是取下次执行时间与系统当前时间做比较，如果下次执行时间晚于系统当前时间，则说明该任务不满足执行条件。<br>反正满足执行条件，对于满足执行条件的任务，需要判断其时间片period的大小，如果是0，说明任务只需要执行一次。反正任务是循环任务。<br>对于period为0的任务，会将其从任务队列中移除，并将任务的标志位置为已执行。<br>对于需要循环执行的任务，会计算出下一次任务将要执行的时间并对相应字段进行设置，之前提到的调度方式有中的schedule与scheduleAtFixedRate的差别在这里也被体现出来，就参数而言，schedule中的period为大于0，scheduleAtFixedRate中的period小于0。<br>最后，对于满足执行条件的任务调用其TimerTask的run方法。<br>对于不满足执行条件的任务进行定时等待，等待时间为executionTime - currentTime。</p>
</blockquote>
<hr>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><blockquote>
<p>1.Timer &amp; TimerTask的基本原理<br>2.Timer的缺点，它始终是单线程的，所以在处理任务时，可能会因为一个长时间的任务而导致其他任务无法被调度。<br>3.Timer中对于任务队列的处理方式（相对有序等思想）</p>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag">#java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/28/java-lock/" rel="next" title="java重入锁分析">
                <i class="fa fa-chevron-left"></i> java重入锁分析
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/28/java定时任务（2）/" rel="prev" title="java定时任务（2）">
                java定时任务（2） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/08/28/java定时任务（1）/"
           data-title="java定时任务（1）" data-url="http://yoursite.com/2016/08/28/java定时任务（1）/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/touxiang.jpg"
               alt="钱伟峰" />
          <p class="site-author-name" itemprop="name">钱伟峰</p>
          <p class="site-description motion-element" itemprop="description">每天进步一点点</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">21</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#TimerTask"><span class="nav-number">1.</span> <span class="nav-text">TimerTask</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-TimerTask主要函数"><span class="nav-number">1.1.</span> <span class="nav-text">1. TimerTask主要函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Timer"><span class="nav-number">2.</span> <span class="nav-text">Timer</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Timer的调度方法"><span class="nav-number">2.1.</span> <span class="nav-text">1.Timer的调度方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-初始化"><span class="nav-number">2.2.</span> <span class="nav-text">2.初始化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-调度过程"><span class="nav-number">2.3.</span> <span class="nav-text">3.调度过程</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钱伟峰</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"qianweifeng"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
